<?php

/**
 * Created by PhpStorm.
 * User: bob
 * Date: 21/9/25
 * Time: 上午10:37
 */

namespace App\Api\Web\Controllers;

use App\Api\Account\Models\SystemMessageUser;
use App\Api\Account\Models\UserAccount;
use App\Api\Account\Services\BusinessService;
use App\Api\Admin\Models\Banner;
use App\Api\Admin\Models\Community;
use App\Api\Admin\Models\Site;
use App\Api\Admin\Models\Subway;
use App\Api\Admin\Models\SubwaySite;
use App\Api\Auth\Models\UsersOpenId;
use App\Api\Web\Models\House;
use App\Api\Web\Models\HouseTag;
use App\Api\Web\Models\HouseWanted;
use App\Api\Web\Models\OrderHouse;
use App\Api\Web\Services\HouseService;
use App\Http\Controllers\Controller;
use App\Libs\Payment\RockyPayLibrary;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class HouseController extends Controller
{
    /**
     * 史上最nb的搜索房源
     * @param Request $request
     * @return array
     */
    public function houseIndex(Request $request)
    {
        $params = $request->all();
        info('house index', $params);
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);
        $keywords = data_get($params, 'keywords', '');
        if (!is_numeric($page) || !is_numeric($pageSize)) {
            throw new \LogicException('系统错误', 120);
        }

        $city = data_get($params, 'city', '');
        if (empty($city)) {
            throw new \LogicException('请先选择城市', 100);
        }
        if (!is_utf8($city)) {
            throw new \LogicException('系统错误', 120);
        }
        $is_social = data_get($params, 'is_social', '');
        $is_need_ding = data_get($params, 'is_need_ding', '');
        $role = data_get($params, 'role', '');
        $orderByAsc = data_get($params, 'order_by_asc', 'desc');
        $orderByName = data_get($params, 'order_by_name', 'id');
        $totalLt = data_get($params, 'total_lt', '');
        $totalGt = data_get($params, 'total_gt', '');
        $lat = data_get($params, 'lat', 37.44328);
        $lng = data_get($params, 'lng', 121.481827);
        if (!empty($lat)) {
            if (!is_numeric($lat)) {
                throw new \LogicException('系统错误', 120);
            }
        }
        if (!empty($lng)) {
            if (!is_numeric($lng)) {
                throw new \LogicException('系统错误', 120);
            }
        }
        if (empty($lat)) {
            $lat = 37.44328;
        }
        if (empty($lng)) {
            $lng = 121.481827;
        }
        $type = data_get($params, 'type', '');      // 1.主卧 2.次卧 3.独卫
        $communityId = data_get($params, 'community_id', '');
        $subwaySiteId = data_get($params, 'subway_site_id', '');

        $m = House::where('house.status', '>=', 200)
            ->join('community as c', 'c.id', '=', 'house.community_id')
            ->leftJoin('users as u', 'house.user_id', '=', 'u.id')
            ->where('c.city', '=', $city)
            ->select('house.*', 'c.name as community_name', 'u.vip_level_int', 'c.near_buildings', 'c.near_bus_stop', 'c.near_company', 'c.near_site1', 'c.near_subway1', 'c.near_site2', 'c.near_subway2', 'c.business', 'c.near_area');

        if (!empty($role)) {
            $m = $m->where('house.role', '=', $role);
        }

        if (!empty($totalLt)) {
            $m = $m->where('total', '>', $totalLt);
        }

        if (!empty($totalLt)) {
            $m = $m->where('total', '<', $totalGt);
        }

        if (!empty($is_social)) {
            $m = $m->where('is_social', '=', $is_social);
        }

        if (!empty($keywords)) {
            $m = $m->where(function ($query) use ($keywords) {
                $query->where('c.name', 'like', "%$keywords%")
                    ->orwhere('c.near_buildings', 'like', "%$keywords%")
                    ->orwhere('c.near_bus_stop', 'like', "%$keywords%")
                    ->orwhere('c.near_company', 'like', "%$keywords%")
                    ->orwhere('c.keywords', 'like', "%$keywords%")
                    ->orwhere('c.near_site1', 'like', "%$keywords%")
                    ->orwhere('c.near_subway1', 'like', "%$keywords%")
                    ->orwhere('c.near_site2', 'like', "%$keywords%")
                    ->orwhere('c.near_subway2', 'like', "%$keywords%")
                    ->orwhere('c.business', 'like', "%$keywords%")
                    ->orwhere('c.near_area', 'like', "%$keywords%");
            });
        }
        switch ($type) {
            case 1:
                $m = $m->where('bedroom_type', '=', 1);
                break;
            case 2:
                $m = $m->where('bedroom_type', '=', 2);
                break;
            case 3:
                $m = $m->where('toilet_type', '=', 1);
        }
        if (!empty($communityId)) {
            $communityIdArr = explode(',', $communityId);
            $m = $m->whereIn('community_id', $communityIdArr);
        }

        if (!empty($subwaySiteId)) {
            $subwaySiteIdArr = explode(',', $subwaySiteId);
            $m = $m->where(function($query) use ($subwaySiteIdArr) {
                $query->whereIn('c.near_site1', $subwaySiteIdArr)
                    ->orWhereIn('c.near_site2', $subwaySiteIdArr);
            });
        }

        if (empty($orderByName)) {
            $orderByName = 'house.id';
        }

        if ($orderByName == 'distance') {
            //round(ACOS(SIN(({$lat} * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS(({$lat} * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS(({$lng} * 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380, 2) distance
            $m = $m->addSelect(\DB::raw("round(ACOS(SIN(({$lat} * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS(({$lat} * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS(({$lng} * 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380, 2) distance"));
            if ($is_need_ding) {
                $m = $m ->orderBy('house.ding_start_at', 'desc');
            }

//                ->orderBy('u.vip_level_int', 'desc')
            $m = $m->orderBy('distance', 'asc')
                ->paginate($pageSize, ['*'], 'page', $page)
                ->toArray();
        } else {
            if ($is_need_ding) {
                $m = $m ->orderBy('house.ding_start_at', 'desc');
            }
            $m = $m
//                ->orderBy('u.vip_level_int', 'desc')
                ->orderBy($orderByName, $orderByAsc)
                ->paginate($pageSize, ['*'], 'page', $page)
                ->toArray();
        }


        foreach ($m['data'] as $k => $v) {
            $m['data'][$k]['role_name'] = data_get(House::$role, data_get($v, 'role', ''), '未知');
            $m['data'][$k]['rent_out_name'] = data_get(House::$rent_out, data_get($v, 'rent_out', ''), '未知');
            $m['data'][$k]['toward_name'] = data_get(House::$toward, data_get($v, 'toward', ''), '未知');
            $m['data'][$k]['facilities_name'] = data_get(House::$facilities, data_get($v, 'facilities', ''), '未知');
            $m['data'][$k]['payment_account_name'] = data_get(House::$payment_account, data_get($v, 'payment_account', ''), '未知');
            $m['data'][$k]['contract_name'] = data_get(House::$contract, data_get($v, 'contract'), '未知');
            $m['data'][$k]['is_has_free_name'] = data_get(House::$is_has_free, data_get($v, 'is_has_free', ''), '未知');
            $m['data'][$k]['is_check_name'] = data_get(House::$is_check, data_get($v, 'is_check', ''), '未知');
            $m['data'][$k]['toilet_type_name'] = data_get(House::$toilet_type, data_get($v, 'toilet_type', ''), '未知');
            $m['data'][$k]['bedroom_type_name'] = data_get(House::$bedroom_type, data_get($v, 'bedroom_type', ''), '未知');
            $m['data'][$k]['sex_limit_name'] = data_get(House::$sex_limit, data_get($v, 'sex_limit', ''), '未知');
            $m['data'][$k]['photos'] = json_decode(data_get($v, 'photos', ''));
            if ($is_need_ding) {
                if (data_get($v, 'ding_start_at', '1970-01-01 00:00:00') > '2000-01-01 00:00:00') {
                    $m['data'][$k]['is_ding'] = 1;
                } else {
                    $m['data'][$k]['is_ding'] = 0;
                }
            }
        }

        return $this->formatOutput($m);

    }

    /**
     * 史上最nb的搜索求租房源
     * @param Request $request
     * @return array
     */
    public function houseWantedIndex(Request $request)
    {
        $params = $request->all();
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);
        $keywords = data_get($params, 'keywords', '');
        if (!is_numeric($page) || !is_numeric($pageSize)) {
            throw new \LogicException('系统错误', 120);
        }
        $city = data_get($params, 'city', '');
        $is_social = data_get($params, 'is_social', '');
        if (!empty($is_social)) {
            if (!is_numeric($is_social)) {
                throw new \LogicException('系统错误', 120);
            }
        }
        if (empty($city)) {
            throw new \LogicException('请先选择城市', 100);
        }
        $orderByAsc = data_get($params, 'order_by_asc', 'desc');
        $orderByName = data_get($params, 'order_by_name', 'id');
        $total = data_get($params, 'total', '');
        $type = data_get($params, 'type', '');      // 1.主卧 2.次卧 3.独卫

        $m = HouseWanted::where('house_wanted.status', '>', -900)
            ->leftJoin('users as u', 'u.id', '=', 'house_wanted.user_id')
            ->select('u.head_img', 'u.name as username', 'house_wanted.*')
            ->where('house_wanted.city', '=', $city);

        if (!empty($keywords)) {
            $m = $m->where(function ($query) use ($keywords) {
                $query->where('house_wanted.name', 'like', "%$keywords%")
                    ->orwhere('house_wanted.position1_name', 'like', "%$keywords%")
                    ->orwhere('house_wanted.position2_name', 'like', "%$keywords%")
                    ->orwhere('house_wanted.position3_name', 'like', "%$keywords%")
                    ->orwhere('house_wanted.position4_name', 'like', "%$keywords%");
            });
        }
        if (!empty($total)) {
            $m = $m->where('house_wanted.total_lt', '<', $total)
                ->where('house_wanted.total_gt', '>', $total);
        }
        if (!empty($is_social)) {
            $m = $m->where('house_wanted.is_social', '=', $is_social);
        }
        switch ($type) {
            case 1:
                $m = $m->where('bedroom_type', '=', 1);
                break;
            case 2:
                $m = $m->where('bedroom_type', '=', 2);
                break;
            case 3:
                $m = $m->where('toilet_type', '=', 1);
            default:
        }


        $m = $m->orderBy($orderByName, $orderByAsc)
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        foreach ($m['data'] as $k => $v) {
            $m['data'][$k]['rent_out'] = data_get(HouseWanted::$rent_out, data_get($v, 'rent_out', ''), '未知');
            $m['data'][$k]['toilet_type'] = data_get(HouseWanted::$toilet_type, data_get($v, 'toilet_type', ''), '未知');
            $m['data'][$k]['bedroom_type'] = data_get(HouseWanted::$bedroom_type, data_get($v, 'bedroom_type', ''), '未知');
        }

        return $this->formatOutput($m);

    }

    /**
     * 客户端修改或者发布房源
     * @param Request $request
     * @return array
     */
    public function releaseOrUpdate(Request $request)
    {
        $params = $request->all();
        $user = authUser();

        $r = HouseService::release($params, 'web', $user->id);
        return $this->formatOutput($r);
    }

    /**
     * 客户端查看我发布的房源
     * @param Request $request
     * @return array
     */
    public function indexMine(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);
        $houses = House::where('status', '>', -900)
            ->orderBy('id', 'desc')
            ->leftJoin('community as c', 'c.id', '=', 'house.community_id')
            ->where('house.user_id', '=', $user->id)
            ->select('house.*', 'c.name as community_name', 'c.near_buildings', 'c.near_bus_stop', 'c.near_company', 'c.near_site1', 'c.near_subway1', 'c.near_site2', 'c.near_subway2', 'c.business', 'c.near_area')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        foreach ($houses['data'] as $k => $v) {
            $houses['data'][$k]['role_name'] = data_get(House::$role, data_get($v, 'role', ''), '未知');
            $houses['data'][$k]['rent_out_name'] = data_get(House::$rent_out, data_get($v, 'rent_out_name', ''), '未知');
            $houses['data'][$k]['toward_name'] = data_get(House::$toward, data_get($v, 'toward', ''), '未知');
            $houses['data'][$k]['facilities_name'] = data_get(House::$facilities, data_get($v, 'facilities', ''), '未知');
            $houses['data'][$k]['payment_account_name'] = data_get(House::$payment_account, data_get($v, 'payment_account', ''), '未知');
            $houses['data'][$k]['contract_name'] = data_get(House::$contract, data_get($v, 'contract'), '未知');
            $houses['data'][$k]['is_has_free_name'] = data_get(House::$is_has_free, data_get($v, 'is_has_free', ''), '未知');
            $houses['data'][$k]['is_check_name'] = data_get(House::$is_check, data_get($v, 'is_check', ''), '未知');
            $houses['data'][$k]['toilet_type_name'] = data_get(House::$toilet_type, data_get($v, 'toilet_type', ''), '未知');
            $houses['data'][$k]['bedroom_type_name'] = data_get(House::$bedroom_type, data_get($v, 'bedroom_type', ''), '未知');
            $houses['data'][$k]['sex_limit_name'] = data_get(House::$sex_limit, data_get($v, 'sex_limit', ''), '未知');
            $houses['data'][$k]['photos'] = json_decode(data_get($v, 'photos', ''));
        }

        return $this->formatOutput($houses);
    }

    /**
     * 客户端查看别人发布的房源
     * @param Request $request
     * @return array
     */
    public function indexOthers(Request $request)
    {
        $params = $request->all();
        $pageSize = data_get($params, 'page_size', 20);
        $userId = data_get($params, 'user_id', '');
        $page = data_get($params, 'page', 1);
        $houses = House::where('status', '>', -900)
            ->orderBy('id', 'desc')
            ->leftJoin('community as c', 'c.id', '=', 'house.community_id')
            ->where('house.user_id', '=', $userId)
            ->select('house.*', 'c.name as community_name',  'c.near_buildings', 'c.near_bus_stop', 'c.near_company', 'c.near_site1', 'c.near_subway1', 'c.near_site2', 'c.near_subway2', 'c.business', 'c.near_area')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        foreach ($houses['data'] as $k => $v) {
            $houses['data'][$k]['role_name'] = data_get(House::$role, data_get($v, 'role', ''), '未知');
            $houses['data'][$k]['rent_out_name'] = data_get(House::$rent_out, data_get($v, 'rent_out_name', ''), '未知');
            $houses['data'][$k]['toward_name'] = data_get(House::$toward, data_get($v, 'toward', ''), '未知');
            $houses['data'][$k]['facilities_name'] = data_get(House::$facilities, data_get($v, 'facilities', ''), '未知');
            $houses['data'][$k]['payment_account_name'] = data_get(House::$payment_account, data_get($v, 'payment_account', ''), '未知');
            $houses['data'][$k]['contract_name'] = data_get(House::$contract, data_get($v, 'contract'), '未知');
            $houses['data'][$k]['is_has_free_name'] = data_get(House::$is_has_free, data_get($v, 'is_has_free', ''), '未知');
            $houses['data'][$k]['is_check_name'] = data_get(House::$is_check, data_get($v, 'is_check', ''), '未知');
            $houses['data'][$k]['toilet_type_name'] = data_get(House::$toilet_type, data_get($v, 'toilet_type', ''), '未知');
            $houses['data'][$k]['bedroom_type_name'] = data_get(House::$bedroom_type, data_get($v, 'bedroom_type', ''), '未知');
            $houses['data'][$k]['sex_limit_name'] = data_get(House::$sex_limit, data_get($v, 'sex_limit', ''), '未知');
            $houses['data'][$k]['photos'] = json_decode(data_get($v, 'photos', ''));
        }

        return $this->formatOutput($houses);
    }

    public function houseDelete(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $id = data_get($params, 'id', '');
        if (empty($id)) {
            throw new \LogicException('缺少必要参数', 100);
        }

        House::where('user_id', '=', $user->id)
            ->where('id', '=', $id)
            ->update([
                'status' => '-900',
            ]);

        return $this->formatOutput('success');
    }

    /**
     * 客户端查看我求租的房源
     * @param Request $request
     * @return array
     */
    public function houseWantedMine(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);
        $houses = HouseWanted::where('status', '>', '-900')
            ->orderBy('id', 'desc')
            ->where('user_id', '=', $user->id)
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        foreach ($houses['data'] as $k => $v) {
            $house['data'][$k]['rent_out_name'] = data_get(HouseWanted::$rent_out, data_get($v, 'rent_out', ''), '未知');
            $house['data'][$k]['toilet_type_name'] = data_get(HouseWanted::$toilet_type, data_get($v, 'toilet_type', ''), '未知');
            $house['data'][$k]['bedroom_type_name'] = data_get(HouseWanted::$bedroom_type, data_get($v, 'bedroom_type', ''), '未知');
        }

        return $this->formatOutput($houses);
    }

    /**
     * 客户端查看别人求租的房源
     * @param Request $request
     * @return array
     */
    public function houseWantedOther(Request $request)
    {
        $params = $request->all();
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);
        $userId = data_get($params, 'user_id', '');
        $houses = HouseWanted::where('status', '>', '-900')
            ->orderBy('id', 'desc')
            ->where('user_id', '=', $userId)
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        foreach ($houses['data'] as $k => $v) {
            $house['data'][$k]['rent_out_name'] = data_get(HouseWanted::$rent_out, data_get($v, 'rent_out', ''), '未知');
            $house['data'][$k]['toilet_type_name'] = data_get(HouseWanted::$toilet_type, data_get($v, 'toilet_type', ''), '未知');
            $house['data'][$k]['bedroom_type_name'] = data_get(HouseWanted::$bedroom_type, data_get($v, 'bedroom_type', ''), '未知');
        }

        return $this->formatOutput($houses);
    }

    public function houseWantedDelete(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $id = data_get($params, 'id', '');
        if (empty($id)) {
            throw new \LogicException('缺少必要参数', 100);
        }

        HouseWanted::where('user_id', '=', $user->id)
            ->where('id', '=', $id)
            ->update([
                'status' => '-900'
            ]);

        return $this->formatOutput('success');
    }

    /**
     * 客户端求租及更改
     * @param Request $request
     * @return array
     */
    public function houseWantedReleaseOrUpdate(Request $request)
    {
        $params = $request->all();
        $user = authUser();

        $r = HouseService::houseWantedReleaseOrUpdate($params, 'web', $user->id);
        return $this->formatOutput($r);
    }

    /**
     * 订房下订单定金
     * @param Request $request
     * @return array
     */
    public function houseOrder(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $houseId = data_get($params, 'house_id', '');
        $isUseIntegral = data_get($params, 'is_use_integral', 0);
        $total = data_get($params, 'total', 0);
        $ding_total = $total;
        if (empty($houseId)) {
            throw new \LogicException('请重新选择房源', 100);
        }
        if ($total <= 0) {
            throw new \LogicException('请确认定金是否正确', 110);
        }

        $integral = 0;
        $bili = 100;
        if ($isUseIntegral) {
            $userAccount = UserAccount::where('user_id', '=', $user->id)
                ->first();
            $integral = data_get($userAccount, 'integral', 0);
            if ($integral >= $total*$bili) {
                $integral = $total*$bili;

                $total = 0;
            } else {
                $total = bcsub($total, $integral/100);
            }

        }

        $house = House::find($houseId);
        $landlordUserId = data_get($house, 'user_id', 0);
        if ($landlordUserId == $user->id) {
            throw new \LogicException('房东不可以租自己的房子哦', 200);
        }
        $isExist = OrderHouse::where('tenement_user_id', '=', $user->id)
            ->where('house_id', '=', $houseId)
            ->where('status', '>', -100)
            ->where('status', '<', 400)
            ->select('id')
            ->first();
        if (!empty($isExist)) {
            throw new \LogicException('已存在进行中的订单', 400);
        }

        $landlordUser = User::find($landlordUserId);
        $order = OrderHouse::create([
            'house_titile' => data_get($house, 'name', ''),
            'house_id' => $houseId,
            'main_img' => data_get($house, 'main_img', ''),
            'stay_date' => data_get($house, 'stay_date', ''),
            'payment_method' => data_get($house, 'payment_account', ''),
            'tenement_user_id' => $user->id,
            'landlord_user_id' => data_get($house, 'user_id', 0),
            'tenement_nickname' => $user->name,
            'landlord_nickname' => data_get($landlordUser, 'name', ''),
            'tenement_headimg' => $user->head_img,
            'landlord_headimg' => data_get($landlordUser, 'head_img', ''),
            'ding_total' => $ding_total,
            'pay_total' => $total,
            'integral' => $integral,
            'status' => -100,
            'is_delete' => 0,
        ]);

        BusinessService::commonTransaction($user->id, -$total, data_get($order, 'id', ''), 'order_house', data_get($order, 'house_titile', '').'支付定金');
        BusinessService::freezeTransaction(data_get($house, 'user_id', 0), $total, data_get($order, 'id', ''), 'order_house', data_get($order, 'house_titile', '').'收到冻结定金');
        BusinessService::commonIntegralTransaction($user->id, -$integral, data_get($order, 'id', ''), 'order_house', data_get($order, 'house_titile', '').'定金积分抵扣');


        $order->update([
            'status' => '100',
            'tenement_status' => '100',
            'landlord_status' => '100',
            'ding_payment_at' => Carbon::now()->toDateTimeString(),
            'meet_time' => Carbon::now()->addDays(5)->toDateTimeString(),
//            'ding_payment_txn' => $notifyInfo['transaction_id'],
        ]);

        SystemMessageUser::create([
            'user_id' => $user->id,
            'type' => 2,
            'message' => '你支付了'.data_get($order, 'house_titile', '').'的定金',
        ]);

        SystemMessageUser::create([
            'user_id' => data_get($house, 'user_id', 0),
            'type' => 2,
            'message' => '你收到'.data_get($user, 'name', '').'的定金',
//            'message' => '有租客定了您的房子'.data_get($order, 'house_titile', ''),
        ]);

        toWxMessage($user, data_get($house, 'user_id', 0), '你收到'.data_get($user, 'name', '').'的定金', '通知');
        toWxMessage(User::find(data_get($house, 'user_id', 0)), $user->id, '你支付了'.data_get($order, 'house_titile', '').'的定金', '通知');
//        $usersOpenId = UsersOpenId::query()
//            ->where('app_id', '=', config("payment.jueqiweilaixcx.wechat.app_id", ''))
//            ->where('user_id', '=', $user->id)
//            ->first();
//        $openId = data_get($usersOpenId, 'open_id');
//        $options = [
//            'order_id' => 'rentding'.Carbon::now()->format('Ymd').data_get($order, 'id'),
//            'notify_url' => env('APP_URL'). '/api/web/house-order/'.data_get($order, 'id').'/mini-payment/notify',
//            'body' => '租房'.data_get($house, 'name', '').'定金',
//            'description' => '租房'.data_get($house, 'name', '').'定金',
//            'openid' => $openId,
//            'total' => $total
//        ];
//        $rockyPay = new RockyPayLibrary('jueqiweilaixcx', 'wechat');
//        $order->payment = $rockyPay->payment('wx_miniapp', $options);

//        $order->payment = $rockyPay->payment('wx_miniapp', $options);

        return $this->formatOutput($order);
    }

    /**
     * 微信小程序支付回调
     * @param Request $request
     * @param $orderId
     * @return string
     */
    public function miniPaymentNotify(Request $request, $orderId)
    {
        $params         = $request->all();
        $order          = OrderHouse::find($orderId);
        $driver         = 'wechat';
        $rockyPay   = new RockyPayLibrary('jueqiweilaixcx', $driver);
        $notifyInfo = $rockyPay->wxMpNotify('wx_miniapp', $params);

        // 支付通知数据获取成功
        if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS' && data_get($order, 'status', 0) == -100) {
            $order->update([
                'status' => '100',
                'tenement_status' => '100',
                'landlord_status' => '100',
                'ding_payment_at' => Carbon::parse($notifyInfo['time_end'])->toDateTimeString(),
                'meet_time' => Carbon::parse($notifyInfo['time_end'])->addDays(5)->toDateTimeString(),
                'ding_payment_txn' => $notifyInfo['transaction_id'],
            ]);
            BusinessService::commonTransaction(data_get($order, 'tenement_user_id', ''), $notifyInfo['total_fee']/100, $orderId, 'order_house', '支付定金'.data_get($order, 'house_titile', ''));
//            $order->attachPaymentTrade($notifyInfo['total_fee'], $method, $paymentAccount, $notifyInfo['transaction_id'], '');
//            $order->save();
        }

        return 'SUCCESS';
    }

    /**
     * 查看订单
     * @param Request $request
     * @return array
     */
    public function houseOrderIndex(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $role = data_get($params, 'role', '');
        $status = data_get($params, 'status', '');
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);

//        if (empty($role)) {
//            throw new \LogicException('缺少必要参数', 100);
//        }

        $m = OrderHouse::leftJoin('house as h', 'h.id', '=', 'order_house.house_id')
            ->where('order_house.status', '>', -900)
            ->select('order_house.*', 'h.total as house_total');
        // landlord
        $roleName = '';
        if ($role == 'user') {
            $m = $m->where('order_house.tenement_user_id', '=', $user->id);
        } elseif ($role == 'landlord') {
            $m = $m->where('order_house.landlord_user_id', '=', $user->id);
        } else {
            $m = $m->where(function($query) use ($user) {
                $query->where('order_house.tenement_user_id', '=', $user->id)
                    ->orWhere('order_house.landlord_user_id', '=', $user->id);
            });
        }

        if (!empty($status)) {
            $m = $m->where('order_house.status', '=', $status);
        }

        $m = $m->orderBy('order_house.id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        foreach ($m['data'] as $k => $v) {
            if (data_get($v, 'landlord_user_id', '') == $user->id) {
                $m['data'][$k]['role_name'] = 'landlord';
            } elseif (data_get($v, 'tenement_user_id', '') == $user->id) {
                $m['data'][$k]['role_name'] = 'user';
            }

            $m['data'][$k]['contract_name'] = data_get(OrderHouse::$contract, data_get($v, 'contract', ''), '未知');
            $m['data'][$k]['payment_method_name'] = data_get(OrderHouse::$payment_method, data_get($v, 'payment_method', ''), '未知');
            $m['data'][$k]['status_name'] = data_get(OrderHouse::$status, data_get($v, 'status', ''), '未知');
            $m['data'][$k]['photos'] = json_decode(data_get($v, 'photos', ''));
        }

        return $this->formatOutput($m);
    }


    /**
     *
     * @param Request $request
     * @return array
     */
    public function orderHouseStatusUpdate(Request $request)
    {
        // 付定金之后，双方都确认看房，房东同意租赁，租客直接租赁交差额，房东完成订单，房源下架
        $params = $request->all();
        $user = authUser();
        $orderId = data_get($params, 'order_id', '');
        $status = data_get($params, 'status', '');
        $role = data_get($params, 'role', '');
        if (empty($status) || empty($orderId) || empty($role)) {
            throw new \LogicException('缺少必要参数', 100);
        }

        $m = OrderHouse::where('id', '=', $orderId);
        if ($role == 'user') {
            $m = $m->where('tenement_user_id', '=', $user->id);
        } else {
            $m = $m->where('landlord_user_id', '=', $user->id);
        }
        $m = $m->first();
        if (empty($m)) {
            throw new \LogicException('未找到该订单', 404);
        }

        $oStatus = data_get($m, 'status', '');
        $paymentAccount = data_get($m, 'payment_method', '');
        $now = Carbon::now()->toDateTimeString();
        $dingPaymentAt = data_get($m, 'ding_payment_at', '');
        $tmptenementStatus = data_get($m, 'tenement_user_id', '');
        $tmplandlordStatus = data_get($m, 'landlord_user_id', '');
        $tmpstatus = data_get($m, 'status', '');
        $ding_total = data_get($m, 'ding_total', '');
        $pay_total = data_get($m, 'pay_total', '');
        $ding_integral = data_get($m, 'ding_integral', '');
        $mm  = clone $m;
        switch ($status) {
            case -200:
                $mm = clone $m;
                switch ($tmpstatus) {
                    case 100:
                        // 如果交定金5天以内，无论谁取消钱退   12.15作废
//                        if (Carbon::parse($dingPaymentAt)->addDays(5)->toDateTimeString() > $now) {
//                            BusinessService::commonTransaction($user->id, $pay_total, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '') . '取消退租金');
//                            BusinessService::commonIntegralTransaction($user->id, $ding_integral, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '') . '取消退积分');
//                            BusinessService::freezeTransaction(data_get($mm, 'landlord_user_id', 0), -$ding_total, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '') . '取消退租金');

//                        }
                        if ($role == 'user') {
                            $m->update([
                                'status' => '-50',
                                'tenement_status' => '-200',
                                'landlord_status' => '-200',
                            ]);
                            // 租客取消进入划拨流程
                            SystemMessageUser::create([
                                'user_id' => $user->id,
                                'type' => 2,
                                'message' => '你取消了和'.data_get($mm, 'landlord_nickname', '').'的租房流程',
                            ]);
                            toWxMessage($user, data_get($mm, 'tenement_user_id', 0), '你取消了和'.data_get($mm, 'landlord_nickname', '').'的租房流程', '通知');
                            SystemMessageUser::create([
                                'user_id' => data_get($mm, 'landlord_user_id', 0),
                                'type' => 2,
                                'message' => data_get($mm, 'tenement_nickname', '').'取消了和你的租房流程',
                            ]);
                            toWxMessage($user, data_get($mm, 'landlord_user_id', 0), data_get($mm, 'tenement_nickname', '').'取消了和你的租房流程', '通知');
                        } else {
                            // 房东取消钱退
                            $m->update([
                                'status' => '-200',
                                'tenement_status' => '-200',
                                'landlord_status' => '-200',
                            ]);
                            BusinessService::commonTransaction(data_get($mm, 'tenement_user_id', ''), $pay_total, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '') . '取消退订金');
                            BusinessService::commonIntegralTransaction(data_get($mm, 'tenement_user_id', ''), $ding_integral, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '') . '取消退积分');
                            BusinessService::freezeTransaction(data_get($mm, 'landlord_user_id', 0), -$ding_total, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '') . '取消退订金');
                            SystemMessageUser::create([
                                'user_id' => data_get($mm, 'landlord_user_id', 0),
                                'type' => 2,
                                'message' => '你取消了和'.data_get($mm, 'tenement_nickname', '').'的租房流程',
                            ]);
                            toWxMessage(User::find(data_get($mm, 'tenement_user_id', 0)), data_get($mm, 'landlord_user_id', 0), '你取消了和'.data_get($mm, 'tenement_nickname', '').'的租房流程', '通知');

                            SystemMessageUser::create([
                                'user_id' => data_get($mm, 'tenement_user_id', 0),
                                'type' => 2,
                                'message' => data_get($mm, 'landlord_nickname', '').'取消了和你的租房流程',
                            ]);
                            toWxMessage($user, data_get($mm, 'tenement_user_id', 0),  data_get($mm, 'landlord_nickname', '').'取消了和你的租房流程', '通知');
                        }

                        break;
                        // 到了确认租环节，用户取消不退，房东取消退
                    case 200:
                    case 300:
                        if ($role == 'user') {
                            // 租客取消进入划拨流程
                            $m->update([
                                'status' => '-50',
                                'tenement_status' => '-200',
                                'landlord_status' => '-200',
                            ]);

                            SystemMessageUser::create([
                                'user_id' => $user->id,
                                'type' => 2,
                                'message' => '你取消了和'.data_get($mm, 'landlord_nickname', '').'的租房流程',
                            ]);
                            toWxMessage($user, data_get($mm, 'tenement_user_id', 0), '你取消了和'.data_get($mm, 'landlord_nickname', '').'的租房流程', '通知');
                            SystemMessageUser::create([
                                'user_id' => data_get($mm, 'landlord_user_id', 0),
                                'type' => 2,
                                'message' => data_get($mm, 'tenement_nickname', '').'取消了和你的租房流程',
                            ]);
                            toWxMessage($user, data_get($mm, 'landlord_user_id', 0), data_get($mm, 'tenement_nickname', '').'取消了和你的租房流程', '通知');
                        } else {
                            // 房东取消退租金
                            $m->update([
                                'status' => '-200',
                                'tenement_status' => '-200',
                                'landlord_status' => '-200',
                            ]);
                            BusinessService::commonTransaction(data_get($mm, 'tenement_user_id', ''), $pay_total, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '') . '取消退订金');
                            BusinessService::commonIntegralTransaction(data_get($mm, 'tenement_user_id', ''), $ding_integral, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '') . '取消退积分');
                            BusinessService::freezeTransaction(data_get($mm, 'landlord_user_id', 0), -$ding_total, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '') . '取消退订金');
                            SystemMessageUser::create([
                                'user_id' => data_get($mm, 'landlord_user_id', 0),
                                'type' => 2,
                                'message' => '你取消了和'.data_get($mm, 'tenement_nickname', '').'的租房流程',
                            ]);
                            toWxMessage(User::find(data_get($mm, 'tenement_user_id', 0)), data_get($mm, 'landlord_user_id', 0), '你取消了和'.data_get($mm, 'tenement_nickname', '').'的租房流程', '通知');

                            SystemMessageUser::create([
                                'user_id' => data_get($mm, 'tenement_user_id', 0),
                                'type' => 2,
                                'message' => data_get($mm, 'landlord_nickname', '').'取消了和你的租房流程',
                            ]);
                            toWxMessage($user, data_get($mm, 'tenement_user_id', 0),  data_get($mm, 'landlord_nickname', '').'取消了和你的租房流程', '通知');
                        }
                }

                break;
            // 已经看房
            case 200:
                if ($oStatus != 100) {
                    throw new \LogicException('订单状态异常', 300);
                }
                if (Carbon::parse($dingPaymentAt)->addDays(5)->toDateTimeString() > $now) {
                    if ($role == 'user') {
                        $m->update([
                            'tenement_status' => 200,
                        ]);
                        SystemMessageUser::create([
                            'user_id' => data_get($mm, 'landlord_user_id', 0),
                            'type' => 2,
                            'message' => '你收到'.data_get($mm, 'tenement_nickname', '').'的看房申请',
                        ]);
                        toWxMessage(User::find(data_get($mm, 'tenement_user_id', '')), data_get($mm, 'landlord_user_id', 0), '你收到'.data_get($mm, 'tenement_nickname', '').'的看房申请', '通知');
                        SystemMessageUser::create([
                            'user_id' => $user->id,
                            'type' => 2,
                            'message' => '你提交了'.data_get($mm, 'house_titile', '').'的看房申请',
                        ]);
                        toWxMessage(User::find(data_get($mm, 'landlord_user_id', '')), data_get($mm, 'tenement_user_id', 0),  '你提交了'.data_get($mm, 'house_titile', '').'的看房申请', '通知');
                    } else {
                        $m->update([
                            'landlord_status' => 200,
                        ]);

                        SystemMessageUser::create([
                            'user_id' => $user->id,
                            'type' => 2,
                            'message' => '你同意'.data_get($mm, 'tenement_nickname', '').'的看房申请',
                        ]);
                        toWxMessage($user, data_get($mm, 'landlord_user_id', 0), '你同意'.data_get($mm, 'tenement_nickname', '').'的看房申请', '通知');

                        SystemMessageUser::create([
                            'user_id' => data_get($mm, 'tenement_user_id', ''),
                            'type' => 2,
                            'message' => '你通过了'.data_get($mm, 'house_titile', '').'的看房申请',
                        ]);
                        toWxMessage($user, data_get($mm, 'tenement_nickname', 0), '你通过了'.data_get($mm, 'house_titile', '').'的看房申请','通知');
                    }
                    $tmporder = OrderHouse::find($orderId);
                    if (data_get($tmporder, 'tenement_status', '') == 200 && data_get($tmporder, 'landlord_status', '') == 200) {
                        $tmporder->update([
                            'status' => 200,
                        ]);
                    }
                } else {
                    throw new \LogicException('已超过5天有效期', 310);
                }
                break;
                // 确认租房 双方
            case 300:
                if ($oStatus != 200) {
                    throw new \LogicException('订单状态异常', 300);
                }
                if ($role == 'user') {
//                    if (data_get($m, 'landlord_status', '') < 300) {
//                        throw new \LogicException('请联系房东同意租赁', 320);
//                    }
//                    $mm = clone $m;
                    $m->update([
                        'tenement_status' => '300',
                        'sure_rent_at' => Carbon::now()->toDateTimeString(),
                    ]);
                    SystemMessageUser::create([
                        'user_id' => data_get($mm, 'landlord_user_id', 0),
                        'type' => 2,
                        'message' => '你收到'.data_get($mm, 'landlord_nickname', '').'的租房申请',
                    ]);
                    toWxMessage($user, data_get($mm, 'landlord_user_id', 0), '你收到'.data_get($mm, 'landlord_nickname', '').'的租房申请', '通知');

                    SystemMessageUser::create([
                        'user_id' => $user->id,
                        'type' => 2,
                        'message' => '你提交了'.data_get($mm, 'house_titile', '').'的租房申请',
                    ]);
                    toWxMessage(User::find(data_get($mm, 'landlord_user_id', 0)), data_get($mm, 'tenement_nickname', 0), '你提交了'.data_get($mm, 'tihouse_titiletle', '').'的租房申请', '通知');

                } else {
                    if (data_get($m, 'tenement_status', '') < 300) {
                        throw new \LogicException('租客还未确认租', 320);
                    }
                    $m->update([
                        'status' => '300',
//                        'tenement_status' => '300',
                        'landlord_status' => '300',
                    ]);

                    SystemMessageUser::create([
                        'user_id' => $user->id,
                        'type' => 2,
                        'message' => '你同意'.data_get($mm, 'landlord_nickname', '').'的租房申请',
                    ]);
                    toWxMessage(User::find(data_get($mm, 'tenement_user_id', '')), data_get($mm, 'landlord_user_id', 0), '你同意'.data_get($mm, 'landlord_nickname', '').'的租房申请', '通知');
                    SystemMessageUser::create([
                        'user_id' => data_get($mm, 'tenement_user_id', ''),
                        'type' => 2,
                        'message' => '你通过了'.data_get($mm, 'house_titile', '').'的租房申请',
                    ]);
                    toWxMessage($user, data_get($mm, 'tenement_user_id', 0), '你通过了'.data_get($mm, 'house_titile', '').'的租房申请', '通知');
                }

                break;
                // 交钱
            case 400:
                if ($tmpstatus != 300) {
                    throw new \LogicException('订单状态异常', 300);
                }
                if ($role == 'user') {
                    switch ($paymentAccount) {
                        case '1':
                            $xishu = 2;
                            break;
                        case '2':
                            $xishu = 4;
                            break;
                        case '3':
                            $xishu = 7;
                            break;
                        case '4':
                            $xishu = 13;
                            break;
                        default:
                            throw new \LogicException('请房东确认支付方式', 310);
                    }
                    $house = House::find(data_get($m, 'house_id'));
                    $pay_total = data_get($m, 'pay_total');
                    $allTotal = data_get($house, 'total', 0) * $xishu;
                    BusinessService::commonTransaction($user->id, -$allTotal, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '').'支付租金');
                    BusinessService::commonTransaction(data_get($house, 'user_id', 0), $allTotal, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '').'收到租金');
                    BusinessService::freezeTransaction(data_get($house, 'user_id', 0), -$pay_total, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '').'定金解冻');
                    BusinessService::commonTransaction(data_get($house, 'user_id', 0), $pay_total, data_get($mm, 'id', ''), 'order_house', data_get($mm, 'house_titile', '').'定金解冻');

                    $m->update([
                        'status' => '400',
                        'tenement_status' => '400',
                        'landlord_status' => '400',
                    ]);
                    SystemMessageUser::create([
                        'user_id' => data_get($mm, 'landlord_user_id', 0),
                        'type' => 2,
                        'message' => '你收到'.data_get($mm, 'tenement_nickname', '').'的支付租金',
                    ]);
                    toWxMessage($user, data_get($mm, 'landlord_user_id', 0), '你收到'.data_get($mm, 'tenement_nickname', '').'的支付租金', '通知');
                    SystemMessageUser::create([
                        'user_id' => $user->id,
                        'type' => 2,
                        'message' => '你支付了'.data_get($mm, 'house_titile', '').'的租金',
                    ]);
                    toWxMessage(User::find(data_get($mm, 'landlord_user_id', 0)), data_get($mm, 'tenement_user_id', 0),  '你支付了'.data_get($mm, 'house_titile', '').'的租金', '通知');
                    House::find(data_get($m, 'house_id'))
                        ->update([
                            'status' => '150',
                        ]);
//                    $m->update([
//                        'tenement_status' => 200,
//                    ]);

                }
        }

        $return =  OrderHouse::find($orderId);
        return $this->formatOutput($return);
    }

    /**
     * 微信小程序支付回调，付房租的回调
     * @param Request $request
     * @param $orderId
     * @return string
     */
    public function payMiniPaymentNotify(Request $request, $orderId)
    {
        $params         = $request->all();
        $order          = OrderHouse::find($orderId);
        $driver         = 'wechat';
        $rockyPay   = new RockyPayLibrary('jueqiweilaixcx', $driver);
        $notifyInfo = $rockyPay->wxMpNotify('wx_miniapp', $params);

        // 支付通知数据获取成功
        if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS' && data_get($order, 'tenement_status', 0) == 200) {
            $order->update([
                'status' => '300',
                'tenement_status' => '300',
                'payment_at' => Carbon::now()->toDateTimeString(),
                'payment_txn' => $notifyInfo['transaction_id'],
            ]);
            BusinessService::commonTransaction(data_get($order, 'tenement_user_id', ''), $notifyInfo['total_fee']/100, $orderId, 'order_house', data_get($order, 'house_titile', '').'支付租金');
//            $order->attachPaymentTrade($notifyInfo['total_fee'], $method, $paymentAccount, $notifyInfo['transaction_id'], '');
//            $order->save();
        }

        return 'SUCCESS';
    }

    public function communityIndex(Request $request)
    {
        $params = $request->all();
        $city = data_get($params, 'city', '');
        $page = data_get($params, 'page', 1);
        $pageSize = data_get($params, 'page_size', 100);

        $r = Community::where('city', '=', $city)
            ->select('name', 'id')
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        return $this->formatOutput($r);
    }

    public function subwayIndex(Request $request)
    {
        $params = $request->all();
        $city = data_get($params, 'city', '');
        $page = data_get($params, 'page', 1);
        $pageSize = data_get($params, 'page_size', 100);

        $r = Subway::where('city', '=', $city)
            ->select('name', 'id')
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        return $this->formatOutput($r);
    }

    public function subwaySiteIndex(Request $request)
    {
        $params = $request->all();
        $subwayId = data_get($params, 'subway_id', '');
        $page = data_get($params, 'page', 1);
        $pageSize = data_get($params, 'page_size', 100);

        $r = Site::where('subway_id', '=', $subwayId)
            ->select('name', 'id')
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        return $this->formatOutput($r);
    }

    public function bannerIndex(Request $request)
    {
        $params = $request->all();
        $page = data_get($params, 'page', 1);
        $pageSize = data_get($params, 'page_size', 100);

        $r = Banner::where('status', '>=', '200')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        return $this->formatOutput($r);
    }


    public function ding(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $id = data_get($params, 'id', '');
        if (empty($id)) {
            throw new \LogicException('缺少必要参数', 100);
        }
        $house = House::where('id', '=', $id)
            ->where('user_id', '=', $user->id)
            ->where('status', '>=', 200)
            ->first();

        if (empty($house)) {
            throw new \LogicException('请等待房源审核通过后刷新', 200);
        }


        BusinessService::commonIntegralTransaction($user->id, -100, data_get($house, 'id', ''), 'house_ding', data_get($house, 'name', '').'置顶刷新');

        $now = Carbon::now()->toDateTimeString();
        $house->update([
            'ding_start_at' => $now,
            'ding_end_at' => '2199-01-01 00:00:00',
        ]);


        return $this->formatOutput('success');
    }
}
